
 /**
 * BaseDAO.java.java.
 * User: BrianChen Date: 2012-6-4 下午08:51:40
 *
 * Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
 * All rights reserved.
 */
package com.collapsar.core.orm.hibernate;


import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.util.Assert;

import com.collapsar.core.orm.model.Entity;
import com.collapsar.core.orm.page.Page;


/**
 * <pre>
 * REVISIONS: 
 * Version 	Date 		Author 			Description
 * ------------------------------------------------------------------- 
 * 1.0 		2012-6-4 	BrianChen 	1. Created this class. 
 * </pre>
 * 
 * @author BrianChen
 * @date 2012-6-4 下午08:51:40
 * @version 1.0
 * @see
 * 数据访问对象（DAO）的基类
 * 包含了按照id存取， 和对全部实体操作的方法，以及日志记录器的实例化
 */
public class BaseHibernateDao extends HibernateDaoSupport{
	protected static final Log logger = LogFactory.getLog(BaseHibernateDao.class);

	/**
	 * 存储 或者 更新 对象
	 * @param entity
	 */
	protected void store(Entity entity){
		this.getHibernateTemplate().saveOrUpdate(entity);
	}
	
//	protected void update(Entity entity){
//		this.getHibernateTemplate().saveOrUpdate(entity);
//	}
	
//	@SuppressWarnings("rawtypes")
//	protected void updateAll(Class clazz, Long ids[]){
//		for(Long id : ids){
//			this.store(this.load(clazz, id));
//		}
//	}	
	
	
	
	/**
	 * 删除  对象
	 * @param entity
	 */
	protected void delete(Entity entity){
		this.getHibernateTemplate().delete(entity);
	}
	
	@SuppressWarnings("rawtypes")
	protected void deleteAll(Class clazz, Long ids[]){
		for(Long id : ids){
			this.delete(this.load(clazz, id));
		}
	}
	
	@SuppressWarnings("rawtypes")
	protected void deleteAll(Collection entities){
		this.getHibernateTemplate().deleteAll(entities);
	}
	
	
	
	/**
	 * 立即向数据库发出查询语句，如果没有相应的数据则直接返回null
	 * @param clazz
	 * @param id
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected Entity get(Class clazz, Long id){
		return (Entity)this.getHibernateTemplate().get(clazz, id);
	}
	/**
	 * load采用延迟加载方式，只返回对象的一个代理（此代理只有一个id属性），只有等到正真使用该对象属性的时候才发出查询
	 * @param clazz
	 * @param id
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	protected Entity load(Class clazz, Long id){
		return (Entity)this.getHibernateTemplate().load(clazz, id);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected List loadAll(Class clazz){
		return this.getHibernateTemplate().loadAll(clazz);
	}
	/**
	 * 分页查询数据
	 * @param offset 当前页偏移量
	 * @param pageSize页面大小
	 * @param hql 查询语句
	 * @param params 查询参数
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected Page findAll(final int offset, final int pageSize, final String hql, final Object... params){
		Assert.hasText(hql, "queryString不能为空");
		
		//获取数据集合
		List records = this.getHibernateTemplate().executeFind(new HibernateCallback(){
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				//设置查询参数
				if(params != null){
					int count = 0;
					for(int i=0; i<params.length; i++){
						if(params[i] != null){
							query.setParameter(count, params[i]);
						}
					}
				}
				query.setFirstResult(offset);
				query.setMaxResults(pageSize);
				return query.list();
			}
		});
		logger.info("result count #####"+ records.size());
		
		//查询总数
		String hqlCount = null;
		int index = hql.indexOf("from");
		if(index != -1){
			hqlCount = "select count(*) " + hql.substring(index);
		}else{
			hqlCount = "select count(*) " + hql;
		}
		int total = ((Long)this.getHibernateTemplate().find(hqlCount).get(0)).intValue();
		logger.info("total count #####"+ total);
		
		return new Page(total, records);
	}
	
	@SuppressWarnings({ "rawtypes"})
	protected List findAll(String hsql){
		return this.getHibernateTemplate().find(hsql);
	}
	
	protected Entity load(Entity entity){
		return this.load(entity.getClass(), entity.getId());
	}
	
	protected void unload(Entity entity){
		try{
			this.getSession().evict(entity);
		}catch(HibernateException ex){
			this.convertHibernateAccessException(ex);
		}
	}
	
	protected void initalize(Object obj){
		this.getHibernateTemplate().initialize(obj);
	}
	
}

